package com.ctshk.rpc.visa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.Currency;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.DateUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.MainDataCurrencyListDTO;
import com.ctshk.rpc.system.dto.MainDataCurrencyQueryDTO;
import com.ctshk.rpc.system.dto.SysDepartmentDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.MainDataCurrencyUpdateStatusReq;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.ISysDepartmentService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.visa.dto.visa.*;
import com.ctshk.rpc.visa.entity.Visa;
import com.ctshk.rpc.visa.entity.VisaFreeCountries;
import com.ctshk.rpc.visa.entity.VisaProduct;
import com.ctshk.rpc.visa.entity.VisaType;
import com.ctshk.rpc.visa.mapper.VisaFreeCountriesMapper;
import com.ctshk.rpc.visa.mapper.VisaMapper;
import com.ctshk.rpc.visa.mapper.VisaProductMapper;
import com.ctshk.rpc.visa.mapper.VisaTypeMapper;
import com.ctshk.rpc.visa.req.visa.*;
import com.ctshk.rpc.visa.service.IVisaService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 签证办理类型 服务实现类
 * </p>
 *
 * @author 陈雷
 * @since 2021-01-22
 */
@DubboService
public class VisaServiceImpl extends ServiceImpl<VisaMapper, Visa> implements IVisaService {
    @Autowired
    private VisaMapper visaMapper;
    @Autowired
    private VisaTypeMapper visaTypeMapper;
    @DubboReference
    IMainDataCurrencyService mainDataCurrencyService;

    @Autowired
    private VisaFreeCountriesMapper visaFreeCountriesMapper;
    @Autowired
    private VisaProductMapper visaProductMapper;

    @DubboReference
    private ISysUserService iSysUserService;
    @DubboReference
    private ISysDepartmentService sysDepartmentService;
    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;

    /**
     * 签证详情
     *
     * @param visaInfoReq
     * @return
     */
    @Override
    public Result<VisaInfoResp> query(VisaInfoReq visaInfoReq) {
        VisaInfoResp visaInfoResp = new VisaInfoResp();
        //获取询价单详情
        QueryWrapper<Visa> visaWrapper = new QueryWrapper<>();
        visaWrapper.eq("is_deleted", 0);
        visaWrapper.eq("id", visaInfoReq.getId());
        Visa visa = visaMapper.selectOne(visaWrapper);
        if (visa == null) {
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        VisaInfoDTO visaInfoDTO = EntityUtil.copy(visa, VisaInfoDTO.class);
        visaInfoDTO.setVisaTypeId(visa.getVisaTypeId().toString());
        visaInfoDTO.setCountryId(visa.getCountryId().toString());
        if (visaInfoDTO.getResponsibleId() != null) {
            //todo   上线去掉
            UserDTO userDTO = null;
            try {
                userDTO = iSysUserService.loadUserByParam(visaInfoDTO.getResponsibleId(), 1);
                SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(visaInfoDTO.getResponsibleId());
//                String userName = userDTO == null ? "" : userDTO.getUsername();
                String userName = userDTO == null ? "" : userDTO.getCnSurname() + userDTO.getCnName();
                String dept = sysDepartmentDTO == null ? "" : sysDepartmentDTO.getTitle();
                visaInfoDTO.setResponsiblenName(userName + "/" + dept);
            } catch (Exception e) {
                Result.failed(SystemError.SYS_500);
            }
        }
//        visaInfoResp.setVisaInfoDTO(visaInfoDTO);
        if (visaInfoDTO.getId() != null) {
            //免签国家
            QueryWrapper<VisaFreeCountries> visaFreeCountriesQueryWrapper = new QueryWrapper<>();
            visaFreeCountriesQueryWrapper.eq("is_deleted", 0);
            visaFreeCountriesQueryWrapper.eq("visa_id", visaInfoDTO.getId());
            List<VisaFreeCountries> visaFreeCountriesList = visaFreeCountriesMapper.selectList(visaFreeCountriesQueryWrapper);
            List<VisaFreeCountriesDTO> visaFreeCountriesDTOList = new ArrayList<>();
            visaFreeCountriesList.forEach(visaFreeCountries -> {
                VisaFreeCountriesDTO visaFreeCountriesDTO = EntityUtil.copy(visaFreeCountries, VisaFreeCountriesDTO.class);
                visaFreeCountriesDTOList.add(visaFreeCountriesDTO);
            });
            //签证办理类型
            QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
            visaTypeQueryWrapper.eq("is_deleted", 0);
            visaTypeQueryWrapper.eq("visa_id", visaInfoDTO.getId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
            List<VisaTypeListDTO> visaTypeListDTOList = new ArrayList<>();
            visaTypeList.forEach(visaType -> {
                visaInfoDTO.setCurrencyId(visaType.getCurrencyId().toString());
                visaInfoDTO.setCurrency(visaType.getCurrency());
                VisaTypeListDTO visaFreeCountriesDTO = EntityUtil.copy(visaType, VisaTypeListDTO.class);
                String typeId = visaType.getTypeId() == null ? null : visaType.getTypeId().toString();
                String supplierId = visaType.getSupplierId() == null ? null : visaType.getSupplierId().toString();
                visaFreeCountriesDTO.setTypeId(typeId);
                visaFreeCountriesDTO.setSupplierId(supplierId);
                visaTypeListDTOList.add(visaFreeCountriesDTO);
            });
            visaInfoResp.setVisaFreeCountriesDTOList(visaFreeCountriesDTOList);
            visaInfoResp.setVisaTypeListDTOList(visaTypeListDTOList);
        }
        visaInfoResp.setVisaInfoDTO(visaInfoDTO);
        return Result.success(visaInfoResp);
    }

    @Override
    public PageResponse<VisaListDTO> list(VisaListReq visaListReq) {
        IPage<Visa> visaIPage = null;
        // 分页条件查询
        QueryWrapper<Visa> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getCountryId()), "country_id", visaListReq.getCountryId());
        wrapper.like(StringUtils.isNotBlank(visaListReq.getName()), "name", visaListReq.getName());
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getVisaTypeId()), "visa_type_id", visaListReq.getVisaTypeId());
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getStatus()), "status", visaListReq.getStatus());
        //预订中心查询有效状态
        if ("1".equals(visaListReq.getNumber())) {
            wrapper.eq("status", 0);
        }
        if (visaListReq.getSupplierId() != null) {
            QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
            visaTypeQueryWrapper.eq("is_deleted", 0);
            visaTypeQueryWrapper.eq("supplier_id", visaListReq.getSupplierId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
            if (visaTypeList.size() >= 1) {
                List<Long> visaIds = new ArrayList<>();
                for (VisaType visaType : visaTypeList) {
                    visaIds.add(visaType.getVisaId());
                }
                wrapper.in("id", visaIds);
            } else {
                Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
                visaIPage = visaMapper.selectPage(iPage, wrapper);
                return PageResponse.empty(visaIPage.getCurrent());
            }

        }
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getResponsibleId()), "responsible_id", visaListReq.getResponsibleId());
        wrapper.eq("is_deleted", 0);
        wrapper.orderByDesc("gmt_create");
        Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
        visaIPage = visaMapper.selectPage(iPage, wrapper);
        if (CollectionUtils.isEmpty(visaIPage.getRecords())) {
            return PageResponse.empty(visaIPage.getCurrent());
        }
        List<VisaListDTO> visaListDTOList = new ArrayList<>();
        visaIPage.getRecords().forEach(visa -> {
            VisaListDTO visaListDTO = EntityUtil.copy(visa, VisaListDTO.class);
            // 获取办理时间
            if (visa.getId() != null) {
                QueryWrapper<VisaType> visaTypeWrapper = new QueryWrapper<>();
                visaTypeWrapper.eq("is_deleted", 0);
                visaTypeWrapper.eq("visa_id", visa.getId());
                List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeWrapper);
                if (visaTypeList != null && visaTypeList.size() >= 1) {
                    List<String> handleDayList = new ArrayList<>();
                    List<String> supplierNames = new ArrayList<>();
                    for (VisaType visaType : visaTypeList) {
                        String typeName = visaType.getTypeName();
                        Integer handleDays = visaType.getHandleDays();
                        handleDayList.add(typeName + " " + handleDays);
                        supplierNames.add(visaType.getSupplierName());
                    }
                    visaListDTO.setHandleDays(handleDayList);
                    visaListDTO.setSupplierNames(supplierNames);
                }
                //获取免签国家
                QueryWrapper<VisaFreeCountries> visaFreeCountriesQueryWrapper = new QueryWrapper<>();
                visaFreeCountriesQueryWrapper.eq("is_deleted", 0);
                visaFreeCountriesQueryWrapper.eq("visa_id", visa.getId());
                List<VisaFreeCountries> visaFreeCountriesList = visaFreeCountriesMapper.selectList(visaFreeCountriesQueryWrapper);
                if (visaFreeCountriesList != null && visaFreeCountriesList.size() > 0) {
                    List<String> freeCountryNames = new ArrayList<>();
                    int i = 1;
                    for (VisaFreeCountries visaFreeCountries : visaFreeCountriesList) {
                        freeCountryNames.add(i + "." + visaFreeCountries.getCountryName());
                        i++;
                    }
                    visaListDTO.setFreeCountryNames(freeCountryNames);
                }
                QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
                visaProductQueryWrapper.eq("visa_id",visa.getId());
                VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
                if (visaProduct == null){
                    throw new BusinessException(SystemError.VISA_ORDER_25012);
                }
                // 签证产品编号
                visaListDTO.setProductNum(visaProduct.getProductNum());
            }
            if (visaListDTO.getResponsibleId() != null) {
                //todo   上线去掉
                UserDTO userDTO = null;
                try {
                    userDTO = iSysUserService.loadUserByParam(visaListDTO.getResponsibleId(), 1);
                    String userName = userDTO == null ? "" : userDTO.getCnSurname() + userDTO.getCnName();
                    SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(visaListDTO.getResponsibleId());
                    String dept = sysDepartmentDTO == null ? "" : sysDepartmentDTO.getTitle();
                    visaListDTO.setResponsiblenName(userName + "/" + dept);
                } catch (Exception e) {
                    Result.failed(SystemError.SYS_500);
                }
            }
            visaListDTOList.add(visaListDTO);
        });
        PageResponse<VisaListDTO> result = new PageResponse<>(visaListDTOList, visaIPage.getCurrent() == 1, visaIPage.getTotal() <= (visaIPage.getCurrent() * visaIPage.getSize()), visaIPage.getTotal(), visaIPage.getCurrent(), visaIPage.getSize());
        return result;
    }

    /**
     * 签证修改状态
     *
     * @param visaUpdateReq
     * @return
     */
    @Override
    public Long update(VisaUpdateReq visaUpdateReq) {
        Visa visa = new Visa();
        visa.setStatus(visaUpdateReq.getStatus());
        visa.setId(visaUpdateReq.getId());
        visaMapper.updateById(visa);
        return visaUpdateReq.getId();
    }


    /**
     * 生成签证产品编号
     * 签证产品编号的生成规则：PV+員工編號+月日4位+時分4位+4位隨機數字
     * @param localDateTime
     * @param userDTO
     * @return
     */
    private String generatorInsuranceNumber(LocalDateTime localDateTime, UserDTO userDTO) {
        String deptCode = userDTO.getDeptCode();
        String employeeNumber = userDTO.getEmployeeNumber();
        String date = DateUtil.fmt(localDateTime, "MMddHHmm");
        String randomNumber = String.valueOf((int) ((Math.random() * 9 + 1) * 1000));
        StringBuffer sb = new StringBuffer();
        sb.append("PV").append(employeeNumber).append(date).append(randomNumber);
        return sb.toString().toUpperCase();
    }

    /**
     * 签证新增
     *
     * @param visaSaveReq
     * @return Result
     */
    @Transactional(rollbackFor = BusinessException.class)
    @Override
    public Long add(VisaSaveReq visaSaveReq, TokenUser user) {
        Visa visaNew = new Visa();
        //操作类型。1 新增,2 修改
        int operateType = NumberConstant.ONE.getValue();
        if (visaSaveReq.getId() != null) {
            Visa visa = visaMapper.selectById(visaSaveReq.getId());
            if (visa == null) {
                throw new BusinessException(SystemError.CUSTOM_3006);
            }
            visaNew = visa;
            operateType = NumberConstant.TWO.getValue();
        }
        Long id = SnowflakeIdWorker.nextId();
        // 国家名称
        visaNew.setCountryName(visaSaveReq.getCountryName());
        // 国家ID
        visaNew.setCountryId(visaSaveReq.getCountryId());
        // 签证名称
        visaNew.setName(visaSaveReq.getName());
        // 签证类型
        visaNew.setVisaType(visaSaveReq.getVisaType());
        // 签证类型ID
        visaNew.setVisaTypeId(visaSaveReq.getVisaTypeId());
        // 负责人员ID
        visaNew.setResponsibleId(visaSaveReq.getResponsibleId());
        // 可停留期限
        visaNew.setStayTime(visaSaveReq.getStayTime());
        // 签证有效期
        visaNew.setVisaVaildDate(visaSaveReq.getVisaVaildDate());
        // 有效次数
        visaNew.setVaildTimes(visaSaveReq.getVaildTimes());
        // 有效次数ID
//        visaNew.setVaildTimesId(visaSaveReq.getVaildTimesId());
        // 送签方式类型
        visaNew.setSendVisaType(visaSaveReq.getSendVisaType());
        // 所需资料
        visaNew.setRequiredInformation(visaSaveReq.getRequiredInformation());
        // 备注
        visaNew.setRemark(visaSaveReq.getRemark());
        // 办理须知
        visaNew.setHandleInstruction(visaSaveReq.getHandleInstruction());
        // 状态：0有效 1无效
        visaNew.setStatus(0);
        // 删除标识
        visaNew.setIsDeleted(0);
        // 来源
        visaNew.setSourceType(1);
        // 附件文件JSON
        visaNew.setFilesJson(visaSaveReq.getFilesJson());
        int result = 0;
        if (operateType == NumberConstant.ONE.getValue()) {
            // 新增
            visaNew.setCreateId(user.getId());
            visaNew.setId(id);
            visaNew.setGmtCreate(LocalDateTime.now());
            result = visaMapper.insert(visaNew);
        } else {
            //修改
            visaNew.setModifiedId(user.getId());
            visaNew.setGmtModified(LocalDateTime.now());
            visaNew.setId(visaSaveReq.getId());
            result = visaMapper.updateById(visaNew);
        }
        if (result <= 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        // 资源产品
        VisaProduct visaProduct = new VisaProduct();
        // 资源来源
        visaProduct.setVisaId(visaNew.getId());
        // 加幅类型 1、加数值 2、加百分比
        visaProduct.setAdjustType(1);
        // 金额
        visaProduct.setAmount(new BigDecimal(0));
        // 创建人
        visaProduct.setCreateId(user.getId());
        // 删除标识
        visaProduct.setIsDeleted(0);
        // 百分比
        visaProduct.setPercent(0.00);
        UserDTO userDTO = iSysUserService.queryCacheUser(user.getId());
        if (userDTO == null) {
            throw new BusinessException(SystemError.USER_1002);
        }
        // 签证产品编号的生成规则：PV+員工編號+月日4位+時分4位+4位隨機數字
        String productNum = generatorInsuranceNumber(LocalDateTime.now(), userDTO);
        if (StringUtils.isEmpty(productNum)){
            throw new BusinessException(SystemError.VISA_ORDER_20016);
        }
        // 产品编号
        visaProduct.setProductNum(productNum);
        // 产品状态
        visaProduct.setStatus(0);
        // 产品来源
        visaProduct.setSourceType(1);
        // 未删除
        visaProduct.setIsDeleted(IsDeletedCode.NO.getCode());
        visaProduct.setGmtCreate(LocalDateTime.now());
        result = visaProductMapper.insert(visaProduct);
        if (result <= 0) {
            throw new BusinessException(SystemError.SYS_437);
        }
        if (visaSaveReq.getVisaFreeCountriesReqList() != null && visaSaveReq.getVisaFreeCountriesReqList().size() > 0) {
            //清空免签国家
            visaFreeCountriesMapper.clearByVisaId(visaNew.getId(), user.getId());
            List<VisaFreeCountries> visaFreeCountriesList = new ArrayList<>();
            for (VisaFreeCountriesReq visaFreeCountriesReq : visaSaveReq.getVisaFreeCountriesReqList()) {
                VisaFreeCountries visaFreeCountries = new VisaFreeCountries();
                // 签证来源
                visaFreeCountries.setVisaId(visaNew.getId());
                // 国家名称
                visaFreeCountries.setCountryName(visaFreeCountriesReq.getCountryName());
                // 国家ID
                visaFreeCountries.setCountryId(visaFreeCountriesReq.getCountryId());
                // 创建时间
                visaFreeCountries.setGmtCreate(LocalDateTime.now());
                // 创建者ID
                visaFreeCountries.setCreateId(user.getId());
                // 删除标识
                visaFreeCountries.setIsDeleted(0);
                visaFreeCountriesList.add(visaFreeCountries);
            }
            Integer batch = visaFreeCountriesMapper.insertBatchSomeColumn(visaFreeCountriesList);
            if (batch < visaFreeCountriesList.size()) {
                throw new BusinessException(SystemError.SYS_437);
            }

        }
        if (visaSaveReq.getVisaTypeReqList() != null && visaSaveReq.getVisaTypeReqList().size() > 0) {

            //清空签证类型
            visaTypeMapper.clearByVisaId(visaNew.getId(), user.getId());
            List<VisaType> visaTypeList = new ArrayList<>();
            String currency = Currency.getCurrencyById(visaSaveReq.getVisaTypeReqList().get(0).getCurrencyId()).getCurrency();
            MainDataCurrencyListDTO currencyByCode = mainDataCurrencyService.getCurrencyByCode(currency);
            BigDecimal plannedExchangeRate = currencyByCode.getPlannedExchangeRate();
            for (VisaTypeReq visaTypeReq : visaSaveReq.getVisaTypeReqList()) {
                VisaType visaType = new VisaType();
                // 所属签证
                visaType.setVisaId(visaNew.getId());
                // 委托类型ID
                visaType.setTypeId(visaTypeReq.getTypeId());
                // 委托类型名称
                visaType.setTypeName(visaTypeReq.getTypeName());
                // 办理时间
                visaType.setHandleDays(visaTypeReq.getHandleDays());
                // 计划悦换率
                visaType.setPlannedExchangeRate(visaTypeReq.getPlannedExchangeRate());
                // 供应商名称
                visaType.setSupplierName(visaTypeReq.getSupplierName());
                if (visaTypeReq.getSupplierId() == null){
                    throw new BusinessException(SystemError.VISA_ORDER_20017);
                }
                // 供应商ID
                visaType.setSupplierId(visaTypeReq.getSupplierId());
                // 创建时间
                visaType.setGmtCreate(LocalDateTime.now());
                // 计算汇率后的成本金额
                /**
                 * 其他币种 ×  计划汇率=港币 + 加幅数值 =售价
                 * 其他币种 × 计划汇率=港币 × （1+加幅百分比）=售价
                 */

                visaType.setCostAmount(visaTypeReq.getCostAmount().multiply(plannedExchangeRate));
                // 币种ID
                visaType.setCurrencyId(visaTypeReq.getCurrencyId());
                // 币种名称
                visaType.setCurrency(visaTypeReq.getCurrency());
                // 创建者ID
                visaType.setCreateId(user.getId());
                // 删除标识
                visaType.setIsDeleted(0);
                visaTypeList.add(visaType);
            }
            Integer batch = visaTypeMapper.insertBatchSomeColumn(visaTypeList);
            if (batch < visaTypeList.size()) {
                throw new BusinessException(SystemError.SYS_437);
            }
        }

        return id;
    }

    /**
     * 签证售卖管理列表
     *
     * @param visaListReq
     * @return PageResponse<VisaSellListRespDTO>
     */
    @Override
    public PageResponse<VisaSellListRespDTO> sellList(VisaListReq visaListReq) {
        IPage<Visa> visaIPage = null;
        // 分页条件查询
        QueryWrapper<Visa> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getCountryId()), "country_id", visaListReq.getCountryId());
        wrapper.like(StringUtils.isNotBlank(visaListReq.getName()), "name", visaListReq.getName());
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getVisaTypeId()), "visa_type_id", visaListReq.getVisaTypeId());
        if (visaListReq.getSupplierId() != null) {
            QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
            visaTypeQueryWrapper.eq("is_deleted", 0);
            visaTypeQueryWrapper.like("supplier_id", visaListReq.getSupplierId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
            if (visaTypeList.size() >= 1) {
                List<Long> visaIds = new ArrayList<>();
                for (VisaType visaType : visaTypeList) {
                    visaIds.add(visaType.getVisaId());
                }
                wrapper.in("id", visaIds);
            } else {
                Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
                visaIPage = visaMapper.selectPage(iPage, wrapper);
                return PageResponse.empty(visaIPage.getCurrent());
            }

        }
        wrapper.eq("is_deleted", 0);
        wrapper.orderByDesc("gmt_create");
        wrapper.groupBy("country_id");
        Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
        visaIPage = visaMapper.selectPage(iPage, wrapper);
        if (CollectionUtils.isEmpty(visaIPage.getRecords())) {
            return PageResponse.empty(visaIPage.getCurrent());
        }
        List<VisaSellListRespDTO> visaSellListRespDTOList = new ArrayList<>();
        visaIPage.getRecords().forEach(visa -> {
            VisaSellListRespDTO visaSellListRespDTO = EntityUtil.copy(visa, VisaSellListRespDTO.class);
            visaSellListRespDTO.setName(visa.getCountryName());
            // 获取办理时间
            if (visa.getCountryId() != null) {
                //根据国家id获取id
                QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
                visaQueryWrapper.eq("is_deleted", 0);
                visaQueryWrapper.eq("country_id", visa.getCountryId());
                List<Visa> visaList = visaMapper.selectList(visaQueryWrapper);
                if (visaList != null && visaList.size() > 0) {
                    List<VisaSellListDTO> visaSellListDTOList = new ArrayList<>();
                    for (Visa visa1 : visaList) {
                        VisaSellListDTO visaSellListDTO = new VisaSellListDTO();
                        visaSellListDTO.setName(visa1.getName());
                        visaSellListDTO.setId(visa1.getId());
                        visaSellListDTO.setVisaType(visa1.getVisaType());
                        QueryWrapper<VisaType> visaTypeWrapper = new QueryWrapper<>();
                        visaTypeWrapper.eq("is_deleted", 0);
                        visaTypeWrapper.in("visa_id", visa1.getId());
                        List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeWrapper);
                        if (visaTypeList != null && visaTypeList.size() >= 1) {
                            List<String> handleDayList = new ArrayList<>();
                            List<String> supplierNames = new ArrayList<>();
                            for (VisaType visaType : visaTypeList) {
                                String typeName = visaType.getTypeName();
                                Integer handleDays = visaType.getHandleDays();
                                handleDayList.add(typeName + " " + handleDays);
                                supplierNames.add(visaType.getSupplierName());
                            }
                            visaSellListDTO.setHandleDays(handleDayList);
                            visaSellListDTO.setSupplierNames(supplierNames);
                            visaSellListDTOList.add(visaSellListDTO);
                        }
                        visaSellListRespDTO.setChildren(visaSellListDTOList);
                    }
                }
            }
            visaSellListRespDTOList.add(visaSellListRespDTO);
        });
        PageResponse<VisaSellListRespDTO> result = new PageResponse<>(visaSellListRespDTOList, visaIPage.getCurrent() == 1, visaIPage.getTotal() <= (visaIPage.getCurrent() * visaIPage.getSize()), visaIPage.getTotal(), visaIPage.getCurrent(), visaIPage.getSize());
        return result;
    }

    /**
     * 签证售卖管理列表2
     *
     * @param visaListReq
     * @return PageResponse<VisaSellListDTO>
     */
    @Override
    public PageResponse<VisaSellListDTO> sellList2(VisaListReq visaListReq) {
        IPage<Visa> visaIPage = null;
        // 分页条件查询
        QueryWrapper<Visa> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getCountryId()), "country_id", visaListReq.getCountryId());
        wrapper.like(StringUtils.isNotBlank(visaListReq.getName()), "name", visaListReq.getName());
        wrapper.eq(StringUtils.isNotBlank(visaListReq.getVisaTypeId()), "visa_type_id", visaListReq.getVisaTypeId());
        wrapper.eq("status", 0);
        if (visaListReq.getSupplierId() != null) {
            QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
            visaTypeQueryWrapper.eq("is_deleted", 0);
            visaTypeQueryWrapper.like("supplier_id", visaListReq.getSupplierId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
            if (visaTypeList.size() >= 1) {
                List<Long> visaIds = new ArrayList<>();
                for (VisaType visaType : visaTypeList) {
                    visaIds.add(visaType.getVisaId());
                }
                wrapper.in("id", visaIds);
            } else {
                Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
                visaIPage = visaMapper.selectPage(iPage, wrapper);
                return PageResponse.empty(visaIPage.getCurrent());
            }

        }
        wrapper.eq("is_deleted", 0);
        wrapper.orderByDesc("gmt_create");
        Page<Visa> iPage = new Page<>(visaListReq.getPageNo(), visaListReq.getPageSize());
        visaIPage = visaMapper.selectPage(iPage, wrapper);
        if (CollectionUtils.isEmpty(visaIPage.getRecords())) {
            return PageResponse.empty(visaIPage.getCurrent());
        }
        List<VisaSellListDTO> visaSellListDTOList = new ArrayList<>();
        visaIPage.getRecords().forEach(visa -> {
            // 获取办理时间
            VisaSellListDTO visaSellListDTO = EntityUtil.copy(visa, VisaSellListDTO.class);
            QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
            visaProductQueryWrapper.eq("visa_id", visa.getId());
            visaProductQueryWrapper.eq("is_deleted", 0);
            VisaProduct product = visaProductMapper.selectOne(visaProductQueryWrapper);
            if (product != null) {
                visaSellListDTO.setAdjustType(product.getAdjustType());
                visaSellListDTO.setAmount(product.getAmount());
                visaSellListDTO.setPercent(product.getPercent());
                visaSellListDTO.setProductNum(product.getProductNum());
            }
            QueryWrapper<VisaType> visaTypeWrapper = new QueryWrapper<>();
            visaTypeWrapper.eq("is_deleted", 0);
            visaTypeWrapper.in("visa_id", visa.getId());
            List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeWrapper);
            if (visaTypeList != null && visaTypeList.size() >= 1) {
                List<String> handleDayList = new ArrayList<>();
                List<String> supplierNames = new ArrayList<>();
                for (VisaType visaType : visaTypeList) {
                    String typeName = visaType.getTypeName();
                    Integer handleDays = visaType.getHandleDays();
                    handleDayList.add(typeName + " " + handleDays);
                    supplierNames.add(visaType.getSupplierName());
                }
                visaSellListDTO.setHandleDays(handleDayList);
                visaSellListDTO.setSupplierNames(supplierNames);
                visaSellListDTOList.add(visaSellListDTO);
            }
        });
        PageResponse<VisaSellListDTO> result = new PageResponse<>(visaSellListDTOList, visaIPage.getCurrent() == 1, visaIPage.getTotal() <= (visaIPage.getCurrent() * visaIPage.getSize()), visaIPage.getTotal(), visaIPage.getCurrent(), visaIPage.getSize());
        return result;
    }

    /**
     * 签证列表
     *
     * @param visaListReq
     * @return
     */
    @Override
    public Result<List<VisaListDTO>> visaList(VisaListReq visaListReq) {
        QueryWrapper<Visa> wrapper = new QueryWrapper<>();
        if (visaListReq.getIds() != null) {
            wrapper.eq("is_deleted", 0);
            wrapper.in("id", visaListReq.getIds());
        } else {
            return Result.success(null);
        }
        List<Visa> visaList = visaMapper.selectList(wrapper);
        List<VisaListDTO> visaListDTOList = new ArrayList<>();
        if (visaList != null) {
            for (Visa visa : visaList) {
                VisaListDTO visaListDTO = EntityUtil.copy(visa, VisaListDTO.class);
                // 获取办理时间
                if (visa.getId() != null) {
                    QueryWrapper<VisaType> visaTypeWrapper = new QueryWrapper<>();
                    visaTypeWrapper.eq("is_deleted", 0);
                    visaTypeWrapper.eq("visa_id", visa.getId());
                    List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeWrapper);
                    if (visaTypeList != null && visaTypeList.size() >= 1) {
                        List<String> handleDayList = new ArrayList<>();
                        List<String> supplierNames = new ArrayList<>();
                        for (VisaType visaType : visaTypeList) {
                            String typeName = visaType.getTypeName();
                            Integer handleDays = visaType.getHandleDays();
                            handleDayList.add(typeName + " " + handleDays);
                            supplierNames.add(visaType.getSupplierName());
                        }
                        visaListDTO.setHandleDays(handleDayList);
                        visaListDTO.setSupplierNames(supplierNames);
                    }
                    //获取免签国家
                    QueryWrapper<VisaFreeCountries> visaFreeCountriesQueryWrapper = new QueryWrapper<>();
                    visaFreeCountriesQueryWrapper.eq("is_deleted", 0);
                    visaFreeCountriesQueryWrapper.eq("visa_id", visa.getId());
                    List<VisaFreeCountries> visaFreeCountriesList = visaFreeCountriesMapper.selectList(visaFreeCountriesQueryWrapper);
                    if (visaFreeCountriesList != null && visaFreeCountriesList.size() > 0) {
                        List<String> freeCountryNames = new ArrayList<>();
                        int i = 1;
                        for (VisaFreeCountries visaFreeCountries : visaFreeCountriesList) {
                            freeCountryNames.add(i + "." + visaFreeCountries.getCountryName());
                            i++;
                        }
                        visaListDTO.setFreeCountryNames(freeCountryNames);
                    }
                }
                if (visaListDTO.getResponsibleId() != null) {
                    //todo   上线去掉try  catch
                    UserDTO userDTO = null;
                    try {
                        userDTO = iSysUserService.loadUserByParam(visaListDTO.getResponsibleId(), 1);
                    } catch (Exception e) {
                        Result.failed(SystemError.SYS_500);
                    }
                    if (userDTO != null) {
                        String userName = userDTO.getUsername();
                        SysDepartmentDTO sysDepartmentDTO = sysDepartmentService.queryByUserId(visaListDTO.getResponsibleId());
                        String dept = sysDepartmentDTO == null ? "" : sysDepartmentDTO.getTitle();
                        visaListDTO.setResponsiblenName(userName + "/" + dept);
                    }
                }
                visaListDTOList.add(visaListDTO);
            }
        }
        return Result.success(visaListDTOList);
    }

    /**
     * 预订中心签证办理详情
     *
     * @param visaInfoReq
     * @return
     */
    @Override
    public Result<VisaHandleResp> visaHandleQuery(VisaInfoReq visaInfoReq) {
        //获取询价单详情
        QueryWrapper<Visa> visaWrapper = new QueryWrapper<>();
        visaWrapper.eq("is_deleted", 0);
        visaWrapper.eq("id", visaInfoReq.getId());
        Visa visa = visaMapper.selectOne(visaWrapper);
        if (visa == null) {
            throw new BusinessException(SystemError.CUSTOM_3000);
        }
        VisaHandleResp visaHandleResp = EntityUtil.copy(visa, VisaHandleResp.class);
        if (null != visa.getVisaTypeId()) {
            visaHandleResp.setVisaTypeId(visa.getVisaTypeId().toString());
        }
        QueryWrapper<VisaType> visaTypeQueryWrapper = new QueryWrapper<>();
        visaTypeQueryWrapper.eq("is_deleted", 0);
        visaTypeQueryWrapper.eq("visa_id", visa.getId());
        List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeQueryWrapper);
        //获取加幅设置
        QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
        visaProductQueryWrapper.eq("is_deleted", 0);
        visaProductQueryWrapper.eq("status", 0);
        visaProductQueryWrapper.eq("visa_id", visa.getId());
        List<VisaProduct> visaProductList = visaProductMapper.selectList(visaProductQueryWrapper);
        if (visaProductList != null && visaProductList.size() >= 1) {
            VisaProduct visaProduct = visaProductList.get(0);
            List<VisaTypeDTO> visaTypeDTOList = new ArrayList<>();
            for (VisaType visaType : visaTypeList) {
                VisaTypeDTO visaTypeDTO = new VisaTypeDTO();
                visaTypeDTO.setId(visaType.getId());
                visaTypeDTO.setTypeId(visaType.getTypeId());
                visaTypeDTO.setTypeName(visaType.getTypeName());
                visaTypeDTO.setCurrency(visaType.getCurrency());
                if (visaProduct.getAdjustType() != null) {
                    BigDecimal amount = new BigDecimal(0);

                    // 换算港币
                    if (visaType.getCostAmount() != null) {
                        // 币种判断
                        if (visaType.getCurrencyId() != null) {
                            MainDataCurrencyUpdateStatusReq mainDataCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
                            mainDataCurrencyUpdateStatusReq.setId(visaType.getCurrencyId());
                            Result<MainDataCurrencyQueryDTO> query = iMainDataCurrencyService.query(mainDataCurrencyUpdateStatusReq);
                            visaType.setCostAmount(visaType.getCostAmount().multiply(query.getData().getPlannedExchangeRate()));
                            //加幅类型
                            if (visaProduct.getAdjustType() == 1) {
                                //加幅值
                                amount = (visaType.getCostAmount() == null ? new BigDecimal("0") : visaType.getCostAmount()).add((visaProduct.getAmount() == null ? new BigDecimal("0") : visaProduct.getAmount()));
                            } else if (visaProduct.getAdjustType() == 2) {
                                //百分比
                                Double percent = visaProduct.getPercent() == null || visaProduct.getPercent().compareTo(new Double(0)) == 0 ? new Double("0") : visaProduct.getPercent();
                                amount = visaType.getCostAmount().add(visaType.getCostAmount().multiply(new BigDecimal(percent)).divide(new BigDecimal("100")));
                            }
                            visaTypeDTO.setAmount(amount);
                        } else {
                            return Result.failed(SystemError.VISA_ORDER_25011);
                        }
                    }
                    visaTypeDTOList.add(visaTypeDTO);
                }
            }
            visaHandleResp.setVisaTypeDTOS(visaTypeDTOList);
        }
        return Result.success(visaHandleResp);
    }

    /**
     * 团订单（旅行团、定制包团）列表
     *
     * @param
     * @return
     */
    @Override
    public Result<List<VisaListGroupDTO>> visaGroupList(VisaListReq visaListReq) {
        QueryWrapper<Visa> wrapper = new QueryWrapper<>();
        if (CollectionUtils.isNotEmpty(visaListReq.getIds())) {
            wrapper.eq("is_deleted", 0);
            wrapper.in("id", visaListReq.getIds());
        } else {
            return Result.success(null);
        }
        List<Visa> visaList = visaMapper.selectList(wrapper);
        List<VisaListGroupDTO> visaListGroupDTOList = new ArrayList<>();
        if (visaList != null) {
            for (Visa visa : visaList) {
                // 获取办理种类
                if (visa.getId() != null) {
                    QueryWrapper<VisaType> visaTypeWrapper = new QueryWrapper<>();
                    visaTypeWrapper.eq("is_deleted", 0);
                    visaTypeWrapper.eq("visa_id", visa.getId());
                    List<VisaType> visaTypeList = visaTypeMapper.selectList(visaTypeWrapper);
                    if (visaTypeList != null && visaTypeList.size() >= 1) {
                        for (VisaType visaType : visaTypeList) {
                            VisaListGroupDTO visaListGroupDTO = EntityUtil.copy(visa, VisaListGroupDTO.class);
                            //查询产品
                            QueryWrapper<VisaProduct> queryWrapper = new QueryWrapper<>();
                            queryWrapper.eq("is_deleted", 0);
                            queryWrapper.eq("visa_id", visaType.getVisaId());
                            VisaProduct visaProduct = visaProductMapper.selectOne(queryWrapper);
                            BigDecimal price = null;
                            if (visaProduct != null) {
                                if (visaProduct.getAdjustType() == 1) {
                                    price = visaType.getCostAmount().add(visaProduct.getAmount());
                                } else if (visaProduct.getAdjustType() == 2) {
                                    price = visaType.getCostAmount().add(visaType.getCostAmount().multiply(new BigDecimal(visaProduct.getPercent())).divide(new BigDecimal("100")));
                                }
                            } else {
                                price = visaType.getCostAmount();
                            }
                            visaListGroupDTO.setPrice(price);
                            visaListGroupDTO.setTypeId(visaType.getTypeId());
                            visaListGroupDTO.setTypeName(visaType.getTypeName());
                            visaListGroupDTOList.add(visaListGroupDTO);
                        }
                    }
                }
            }
        }
        return Result.success(visaListGroupDTOList);
    }

    /**
     * 团订单（旅行团、定制包团）获取价格
     *
     * @param visaGroupPriceReq
     * @return VisaListGroupDTO
     */
    @Override
    public Result<VisaGroupDetailDTO> visaGroupDetail(VisaGroupPriceReq visaGroupPriceReq) {
        //获取签证类型
        QueryWrapper<VisaType> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("visa_id", visaGroupPriceReq.getVisaId());
        queryWrapper.eq("type_id", visaGroupPriceReq.getTypeId());
        VisaType visaType = visaTypeMapper.selectOne(queryWrapper);
        //获取产品
        QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
        visaProductQueryWrapper.eq("is_deleted", 0);
        visaProductQueryWrapper.eq("visa_id", visaGroupPriceReq.getVisaId());
        VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
        VisaGroupDetailDTO visaGroupDetailDTO = new VisaGroupDetailDTO();
        BigDecimal price = null;
        if (visaType != null && visaProduct != null) {
            visaGroupDetailDTO.setTypeId(visaType.getTypeId());
            visaGroupDetailDTO.setTypeName(visaType.getTypeName());
            if (visaProduct.getAdjustType() == 1) {
                price = visaType.getCostAmount().add(visaProduct.getAmount());
            } else if (visaProduct.getAdjustType() == 2) {
                price = visaType.getCostAmount().add(visaType.getCostAmount().multiply(new BigDecimal(visaProduct.getPercent())).divide(new BigDecimal("100")));
            }
        }
        visaGroupDetailDTO.setAmount(price);
        visaGroupDetailDTO.setId(Long.parseLong(visaGroupPriceReq.getVisaId()));
        return Result.success(visaGroupDetailDTO);
    }

    /**
     * 根据ID列表获取签证详情（内部接口）
     *
     * @param visaIdList
     */
    @Override
    public List<TripVisaDTO> queryByIdList(List<Long> visaIdList) {
        return visaMapper.queryByIdList(visaIdList);
    }
}

